package ic.doc.web;

import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.simpleframework.http.Request;
import org.simpleframework.http.Response;
import org.simpleframework.http.core.Container;
import org.simpleframework.transport.connect.Connection;
import org.simpleframework.transport.connect.SocketConnection;

import com.wolfram.alpha.WAEngine;
import com.wolfram.alpha.WAException;
import com.wolfram.alpha.WAPlainText;
import com.wolfram.alpha.WAPod;
import com.wolfram.alpha.WAQuery;
import com.wolfram.alpha.WAQueryResult;
import com.wolfram.alpha.WASubpod;

public class SimpleServer implements Container {

    public void handle(Request request, Response response) {

        String result = "";
    	try {
            String q = request.getParameter("q");
            System.out.println("q=" + q);

//            q = "what is 9 plus 2";
            String appid = "V4YJL5-9LJT4QJ85Q";
            System.out.println(q);
            
            
         // Use "pi" as the default query, or caller can supply it as the lone command-line argument.
            String input = q;
            
            // The WAEngine is a factory for creating WAQuery objects,
            // and it also used to perform those queries. You can set properties of
            // the WAEngine (such as the desired API output format types) that will
            // be inherited by all WAQuery objects created from it. Most applications
            // will only need to crete one WAEngine object, which is used throughout
            // the life of the application.
            WAEngine engine = new WAEngine();
            
            // These properties will be set in all the WAQuery objects created from this WAEngine.
            engine.setAppID(appid);
            engine.addFormat("plaintext");

            // Create the query.
            WAQuery query = engine.createQuery();
            
            // Set properties of the query.
            query.setInput(input);
            
            try {
                // For educational purposes, print out the URL we are about to send:
//                System.out.println("Query URL:");
//                System.out.println(engine.toURL(query));
//                System.out.println("");
                
                // This sends the URL to the Wolfram|Alpha server, gets the XML result
                // and parses it into an object hierarchy held by the WAQueryResult object.
                WAQueryResult queryResult = engine.performQuery(query);
                
                if (queryResult.isError()) {
                    System.out.println("Query error");
                    System.out.println("  error code: " + queryResult.getErrorCode());
                    System.out.println("  error message: " + queryResult.getErrorMessage());
                } else if (!queryResult.isSuccess()) {
                    System.out.println("Query was not understood; no results available.");
                } else {
                    // Got a result.
//                    System.out.println("Successful query. Pods follow:\n");
                    boolean found = false;
                    for (WAPod pod : queryResult.getPods()) {
                        if (!pod.isError()) {
                        	
                        	if (pod.getTitle().equals("Result")){
                        		found = true;
                        	}
                        	
                            System.out.println(pod.getTitle());
                            System.out.println("------------");
                            for (WASubpod subpod : pod.getSubpods()) {
                                for (Object element : subpod.getContents()) {
                                    if (element instanceof WAPlainText) {
                                    	String outText = ((WAPlainText) element).getText();
                                        System.out.println(outText);
                                        System.out.println("");
                                        if (found){
                                        	result = outText;
                                        	try{
	                                        	String[] seperated = result.split(":");
	                                        	result = seperated[1];
                                        	}catch (Exception e) {
												// TODO: handle exception
                                        		result =outText;
											}
                                        	System.out.println("found result =" + result);
                                        	break;
                                        }
                                        if (found)
                                        	break;
                                    }
                                    if (found)
                                    	break;
                                }
                                if (found)
                                	break;
                            }
                            if (found)
                            break;
                            
                            System.out.println("");
                        }
                    }
                    // We ignored many other types of Wolfram|Alpha output, such as warnings, assumptions, etc.
                    // These can be obtained by methods of WAQueryResult or objects deeper in the hierarchy.
                }
            } catch (WAException e) {
                e.printStackTrace();
            }
            
            
            System.out.println("To result mas ine: " + result);
            PrintStream body = response.getPrintStream();
            body.println(result);

            body.close();

        } catch (Throwable e) {
            // stop simpleframework swallowing exceptions without us seeing them...
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        Container container = new SimpleServer();
        Connection connection = new SocketConnection(container);
        SocketAddress address = new InetSocketAddress(8080);
        connection.connect(address);
    }
}



//StringBuffer sb = new StringBuffer(q);
//int plus = sb.indexOf("plus");
//if (plus!= -1){
//	int first = Integer.parseInt(sb.indexOf("is")+2);
//}
//
////Console c = System.console();
////String ans = c.readLine(q+": ");
